﻿var ws;
var ws_ip;
var ws_port;

var msg_model = function() {
	Type = -1;
	Data = "";
}

// 连接服务器
function connect() {
	ws = new WebSocket("ws://" + ws_ip + ":" + ws_port);

	ws.onopen = function() {
		// Log("连接成功");
		$("#btnPhoneStatus").text("连接成功");
		$("#btnPhoneStatus").removeClass("disabled");
	};

	ws.onclose = function(evt) {
		// Log("连接断开，断线重连");
		$("#btnPhoneStatus").text("重新连接...");
		setTimeout("reconnect()", 2000);
	};
	ws.onerror = function(evt) {
		// Log("连接服务器失败");
		$("#btnPhoneStatus").text("连接失败");
		$("#btnPhoneStatus").addClass("disabled");
	};

	ws_event();
}

// 断线重连
function reconnect() {
	ws = new ReconnectingWebSocket("ws://" + ws_ip + ":" + ws_port);
	ws_event();
}

// 设置事件
function ws_event() {
	ws.onmessage = function(evt) {
		var obj = eval("(" + evt.data + ")");

		switch (obj.Type) {
		case 5: // 收到来电

			var line = eval("(" + obj.Data + ")");

			//Log("来电号码：" + line.LocalPhone + " _ " + line.Phone);
			if (ccAgantNumber.indexOf(line.LocalPhone)>-1) {
				isperp.openDialog({
					"contentUrl" : "callcenter/config/openEdit?caller=" + line.Phone
				});
			}
			break;

		case 6: // 未接来电
			var line = eval("(" + obj.Data + ")");
			// Log("未接来电：" + line.LocalPhone + " _ " + line.Phone);
			break;

		case 7:
			break;

		case 8: // 挂机
			var line = eval("(" + obj.Data + ")");
			// Log("挂机：" + line.LocalPhone + "_" + line.FilePath);
			break;

		case 9: // 摘机
			var line = eval("(" + obj.Data + ")");
			// Log("摘机：" + line.LocalPhone);
			break;

		case 12: // 呼出
			var line = eval("(" + obj.Data + ")");
			// Log("呼出：" + line.LocalPhone + " _ " + line.Phone);
			break;

		case 15: // 拨号结果
			var r = eval("(" + obj.Data + ")");
			// Log("呼出：" + r.Line + "_" + r.Msg);
			break;
		}
	};
}

function call() {
	var local_phone = "1"; // 通道1
	var remote_phone = $("#num").val();

	var m = new msg_model();
	m.Type = 1;
	m.Data = "{\"Param1\":\"" + local_phone + "\",\"Param2\":\"" + remote_phone + "\"}";

	sendWs(m);
}

function sendWs(obj) {
	ws.send(MsgToJson(obj));
}

function Log(msg) {
	console.log(msg);
	$("body").append(msg + "</br>");
}

function MsgToJson(obj) {
	return "{'Type':'" + obj.Type + "','Data':'" + obj.Data + "'}";
}